package com.unibuy.smartdevice.ui.devs.flower;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.unibuy.smartdevice.FragmentAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.controller.DevController;
import com.unibuy.smartdevice.databinding.RecyclerFlowerBuyListBinding;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.dialog.BuyDialog;
import com.unibuy.smartdevice.ui.tools.ImageGlide;

import java.util.List;

public class RecyclerFlowerBuyListAdpter extends RecyclerView.Adapter<RecyclerFlowerBuyListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private final List<SlotStructure> SlotList;
    private FragmentAbstract fragment;

    public RecyclerFlowerBuyListAdpter(FragmentAbstract fragment, List<SlotStructure> slotList) {
        this.logs = new Logs(this.getClass());
        this.context = fragment.getContext();
        this.SlotList = slotList;
        this.fragment = fragment;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerFlowerBuyListBinding binding;

        public ViewHolder(@NonNull RecyclerFlowerBuyListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 來綁定佈局
        RecyclerFlowerBuyListBinding binding = RecyclerFlowerBuyListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SlotStructure slot = SlotList.get(position);
        String urlString = slot.getProduct().getProductImg();
        try {
            new ImageGlide(context).fileload(urlString, holder.binding.imageProductPicture);
        } catch (LogsEmptyException e) {
            this.logs.warning(e);
        }
        holder.binding.textSlot.setText(String.format("%03d", slot.getSlot()));
        holder.binding.textProductName.setText(slot.getProduct().getProductName());

        int machinePrice = slot.getProduct().getMachinePrice();
        int sellingPrice = slot.getProduct().getSellingPrice();
        int memberPrice = slot.getProduct().getMemberPrice();
        int slotUpperLimit = slot.getProduct().getSlotUpperLimit();
        int count = slot.getCount();
        boolean isLock = slot.isLock();

        int price = machinePrice > 0? machinePrice: sellingPrice;

        holder.binding.textPrice.setText("NT$ "+price);

        holder.binding.mask.setVisibility(View.GONE);
        holder.binding.textMask.setText("");

        if (count <= 0) {
            holder.binding.mask.setVisibility(View.VISIBLE);
            holder.binding.textMask.setText("已經售完");
        }

        if (isLock) {
            holder.binding.mask.setVisibility(View.VISIBLE);
            holder.binding.textMask.setText("暫停販售");
        }

        if (count > 0 && !isLock) {
            holder.binding.imageProductPicture.setOnClickListener(new imageProductPictureOnClickListener(position));
        } else {
            holder.binding.imageProductPicture.setOnClickListener(null);
        }
    }

    @Override
    public int getItemCount() {
        return SlotList.size();
    }

    public void addSlotData(SlotStructure slotStructure) {
        SlotList.add(slotStructure);
        notifyItemInserted(SlotList.size() -1);
    }

    public class imageProductPictureOnClickListener implements View.OnClickListener {
        private int position;

        public imageProductPictureOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
//            SlotStructure slotProduct = SlotList.get(position);
//            if (slotProduct.isLock()) return;
//            if (MyApp.getInstance().isShowDialog) return;
//
////            SlotStructure slotProduct = SlotList.get(position);
//            BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
//            MyApp.getInstance().getBuyList().add(buyProduct);
//            fragment.getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
//            new BuyDialog(context, fragment.getSrcHandlerMain()).show();
//
////            MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevDetectSlotByVMC(fragment.getSrcHandlerMain(), position), 2000L);
////            MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().checkSlot(slotProduct.getSlot()));
            SlotStructure slotProduct = SlotList.get(position);
            if (slotProduct.isLock()) return;
            if (MyApp.getInstance().isShowDialog) return;

            int slotnum = position +1;
            new AlertDialog.Builder(context)
                    .setTitle("購買確認")
                    .setMessage("是否確定要購買第 "+ slotnum +" 號格子櫃的商品？")
                    .setPositiveButton("確認", (dialog, which) -> {
                        BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
                        MyApp.getInstance().getBuyList().add(buyProduct);
                        fragment.getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
                        new BuyDialog(context, fragment.getSrcHandlerMain()).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }

    public class DevDetectSlotByVMC extends DevController.ReadBufferOnScheduler {
        private int position;

        public DevDetectSlotByVMC(HandlerMain handlerMain, int position) {
            super(handlerMain);
            this.position = position;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }

        @Override
        public void readBufferOnScheduler(DevController devController, HandlerMain handlerMain) {
            for (byte[] buffer: devController.getReadBufferByMax()) {
                if (buffer[0] == 0x02 && buffer[1] == 0x01 || buffer[0] == 0x02 && buffer[1] == 0x02 || buffer[0] == 0x02 && buffer[1] == 0x04) {
                    SlotStructure slotProduct = SlotList.get(position);
                    BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
                    MyApp.getInstance().getBuyList().add(buyProduct);
                    handlerMain.start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
                    new BuyDialog(context, fragment.getSrcHandlerMain()).show();

                    return;
                }
            }

            handlerMain.start(getClass().getSimpleName(), "@貨道尚未準備好，三秒後再點選");
        }
    }
}
